/**
* @author   Frederic Saunier - www.tekool.net
* @since    2008/08/10
*
* Copyright (C) 2006 Frederic Saunier
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*
*/

package net.tekool.projects.objscomp.commands;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
 * @author Administrateur
 *
 */
public class WriteCode
{
	private String code;
	private String outputFilePath;
	
	/**
	 * Constructor
	 *
	 * @param outputFilePath
	 * 			The output file path to which to write the code.
	 * @param code
	 * 			The input code to write.
	 */
	public WriteCode(String code, String outputFilePath)
    {
	    super();
	    
	    this.code = code;
	    this.outputFilePath = outputFilePath;
    }
	
	/**
	 * Executes the command.
	 */
	public void execute()
	{
		write();
	}

	/**
	 * Write the code to given output file.
	 */
	private void write()
    {
		File file = new File(outputFilePath);
				
		if(file.exists())
		{
			if(!file.canWrite())
				throw (new Error(file.getAbsolutePath() + " is not writable."));
		}
		else
		{
			try
			{
				if(!file.exists())
					file.createNewFile();
			}
			catch(IOException e)
			{
				throw (new Error("Error creating " + file.getPath()));
			}

		}
		
		FileWriter writer;
		try
		{
			writer = new FileWriter(file);
			writer.write(code);
			writer.close();
		}
		catch(FileNotFoundException e)
		{
			throw (new Error(file.getPath() + " not found"));
		}
		catch(IOException e)
		{
			throw (new Error("Error writing to " + file.getPath()));
		}
    }
}